package aaa;

import com.baidu.bjf.remoting.protobuf.utils.compiler.ClassUtils;

import javax.tools.SimpleJavaFileObject;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URI;

public  class JavaFileObjectImpl extends SimpleJavaFileObject {

    /** The bytecode. */
    private ByteArrayOutputStream bytecode;

    /** The source. */
    private final CharSequence source;

    /**
     * Instantiates a new java file object impl.
     *
     * @param baseName the base name
     * @param source the source
     */
    public JavaFileObjectImpl(final String baseName, final CharSequence source) {
        super(ClassUtils.toURI(baseName + ClassUtils.JAVA_EXTENSION), Kind.SOURCE);
        this.source = source;
    }

    /**
     * Instantiates a new java file object impl.
     *
     * @param name the name
     * @param kind the kind
     */
    JavaFileObjectImpl(final String name, final Kind kind) {
        super(ClassUtils.toURI(name), kind);
        source = null;
    }

    /**
     * Instantiates a new java file object impl.
     *
     * @param uri the uri
     * @param kind the kind
     */
    public JavaFileObjectImpl(URI uri, Kind kind) {
        super(uri, kind);
        source = null;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.tools.SimpleJavaFileObject#getCharContent(boolean)
     */
    @Override
    public CharSequence getCharContent(final boolean ignoreEncodingErrors) throws UnsupportedOperationException {
        if (source == null) {
            throw new UnsupportedOperationException("source == null");
        }
        return source;
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.tools.SimpleJavaFileObject#openInputStream()
     */
    @Override
    public InputStream openInputStream() {
        return new ByteArrayInputStream(getByteCode());
    }

    /*
     * (non-Javadoc)
     *
     * @see javax.tools.SimpleJavaFileObject#openOutputStream()
     */
    @Override
    public OutputStream openOutputStream() {
        return bytecode = new ByteArrayOutputStream();
    }

    /**
     * Gets the byte code.
     *
     * @return the byte code
     */
    public byte[] getByteCode() {
        if (bytecode == null) {
            return null;
        }
        return bytecode.toByteArray();
    }
}
